package com.leboncoin.batch;

import java.util.logging.Logger;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.leboncoin.bean.SearchItemBean;
import com.leboncoin.bean.SubscriptionBean;
import com.leboncoin.xml.ConfigManager;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.SeleneseTestCase;

public class FullSearch extends SeleneseTestCase {
	
	protected static Logger logger = Logger.getLogger(FullSearch.class.getName());	
	ConfigManager configManager = null;
	
	@Before
	public void setUp() throws Exception {

		configManager = new ConfigManager("conf/fullSearch.xml");

		selenium = new DefaultSelenium("choraledecournon.dyndns.org", 4444, "*chrome", "http://www.leboncoin.fr/");
		selenium.start();
	}

	@Test
	public void testSearch() throws Exception {
		
		for (SubscriptionBean subscriptionBean:configManager.getSubscriptions()){

			CommonSearch commonSearch = CommonSearch.getInstance(selenium);
			commonSearch.searchFromSubscription(false, subscriptionBean);
			EntityManagerFactory emf = null;
			EntityManager em = null;
			EntityTransaction transac = null;
			try {
				emf = Persistence.createEntityManagerFactory("leboncoin");
				em = emf.createEntityManager();
				transac = em.getTransaction();
				transac.begin();
				
				for (SearchItemBean searchItemBean:subscriptionBean.getSearchItems()){
					em.merge(searchItemBean);
				}

				
				transac.commit();
			} catch (Exception e){
				logger.severe(e.getMessage());
				if (e.getCause() != null){
					logger.severe(e.getCause().getMessage());
				}
				if (transac != null && transac.isActive()) transac.rollback();
			} finally {
				if (em != null) em.close();
				if (emf != null) emf.close();
			}
		}
		
	}


	
	@After
	public void tearDown() throws Exception {
		selenium.stop();
	}


}
